package com.ihrm.company.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.dao.CompanyDao;
import com.ihrm.company.mapper.CompanyMapper;
import com.ihrm.company.mapper.DepartmentMapper;
import com.ihrm.domain.company.CoCompany;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.company.vo.OrgThreeInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private IdWorker idWorker;
    /**
     * 保存部门
     *  1.配置idwork到工程
     *  2.在service中注入idwork
     *  3.通过idwork生成id
     *  4.保存部门
     */
    public void add(Department department) {
        //基本属性的设置
        String id = idWorker.nextId()+"";
        department.setId(id);
        departmentMapper.insert(department);
    }

    /**
     * 更新企业
     *  1.参数：Company
     *  2.根据id查询企业对象
     *  3.设置修改的属性
     *  4.调用dao完成更新
     */
    public void update(Department department,String id) {
        Department temp = departmentMapper.selectById(id);
        temp.setName(department.getName());
        temp.setManager(department.getManager());
        departmentMapper.updateById(temp);
    }


    /**
     * 删除部门
     */
    public void deleteById(String id) {
        departmentMapper.deleteById(id);
    }

    /**
     * 根据name查询部门
     */
    public List<Department> findByName(String name) {
        QueryWrapper<Department> qw = new QueryWrapper<>();
        qw.like("name", name); // eq 是用来设置等值条件，这里根据 "name" 字段查找
        return departmentMapper.selectList(qw);// 使用 selectOne 获取单条记录
    }

    /**
     * 查询部门列表
     */
    public List<OrgThreeInfoVo> findAll() {
        //一次把所有的数据都查出来
        List<Department> departments = departmentMapper.findAll();
        List<OrgThreeInfoVo> allList = departments.stream().map(p -> {
            OrgThreeInfoVo vo = new OrgThreeInfoVo();
            BeanUtils.copyProperties(p, vo);
            return vo;
        }).collect(Collectors.toList());
        //指定根节点的parentId]
        return buildChildren("0", allList);
    }

    private List<OrgThreeInfoVo> buildChildren(String parentId, List<OrgThreeInfoVo> allList){
        List<OrgThreeInfoVo> voList = new ArrayList<>();
        for (OrgThreeInfoVo item : allList) {
            //如果相等
            if (Objects.equals(item.getPid(), parentId)) {
                //递归，自己调自己
                item.setChildrenList(buildChildren(item.getId(), allList));
                voList.add(item);
            }
        }
        return voList;
    }

}
